package cn.wolfcode.crm.realm;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.service.IEmployeeService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class MyRealm extends AuthorizingRealm {
    @Override
    public String getName() {
        return "MyRealm";
    }

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Employee employee = (Employee) principals.getPrimaryPrincipal();
        if (employee.getAdmin()) {
            info.addStringPermission("*:*");
            info.addRole("admin");
        } else {
            List<String> permissions = permissionMapper.getPermissionByEmployeeId(employee.getId());
            info.addStringPermissions(permissions);
            List<String> roleSns = roleMapper.getRoleSnByEmployeeId(employee.getId());
            info.addRoles(roleSns);
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String) token.getPrincipal();
        Employee employee = employeeService.getEmployeeByUsername(principal);
        if (employee == null || employee.getState() == false) {
            return null;
        }
        return new SimpleAuthenticationInfo(employee, employee.getPassword(),
                ByteSource.Util.bytes(employee.getUsername()), this.getName());
    }
    @Test
    public void testCryptography() throws Exception {
        //md5加密，加盐，一次散列
        String password_md5_salt_1 = new Md5Hash("1", "admin", 2).toString();
        System.out.println(password_md5_salt_1);
    }
}
